package com.example.demo.java8.stream;

import com.example.demo.model.Person;
import com.example.demo.model.Student;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 *
 * groupingBy 使用
 *
 * @author luowj12
 * @since 2021/5/27 16:34
 */
public class GroupByTest {

    public static void main(String[] args) {
        //3 apple, 2 banana, others 1
        List<String> items =
                Arrays.asList("apple", "apple", "banana",
                        "apple", "orange", "banana", "papaya");
        //统计key的个数
        Map<String, Long> result =items
                .stream()
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
        //System.out.println(result);

        Map<String, List<String>> result2 =items
                .stream()
                .collect(Collectors.groupingBy(v->v));
        //System.out.println(result2);

        List<Student> sList = new ArrayList<>();
        Student s1 = new Student("aa",2);
        Student s2 = new Student("aa",3);
        Student s3 = new Student("bb",3);
        sList.add(s1);
        sList.add(s2);
        sList.add(s3);
        Map<String,List<Student>> sMap = sList.stream()
                .collect(Collectors.groupingBy(Student::getName));
        //name相同 sex相加
        Map<String,Integer> sMap2 = sList.stream()
                .collect(Collectors.groupingBy(Student::getName,Collectors.summingInt(Student::getSex)));
        //name相同 sex添加到list中
        Map<String,List<Integer>> sMap3 = sList.stream()
                .collect(Collectors.groupingBy(Student::getName,
                        Collectors.mapping(Student::getSex, Collectors.toList())));
        Map<String, String> sMap4 = sList.stream().collect(Collectors.groupingBy(Student::getName,
                Collectors.mapping(Student::getName, Collectors.joining(", ", "Names: [", "]"))));
        System.out.println(sMap);
        System.out.println(sMap2);
        System.out.println(sMap3);
        System.out.println(sMap4);

    }

}
